c        for bash, the file name will be assigned from bash command
c        about input:
c        file name in main function, like here saf2-left.txt
c        long0, lat0, d, in subroutine xy2deg1. they are center coor
c                       and rotate angle
      program xy2deg
          implicit real*8(a-h,l,o-z)

          dimension coor4(4,10000), coor4deg(4,10000)
          dimension nleft(10000),nright(10000)
          character*79 buffer
          integer::status=0
          integer linenum
          character*100 arg, inputfile,outputfile
          integer*4 k

          call getarg(1,arg)
          inputfile=arg
          outputfile=inputfile(1:len_trim(inputfile)-3)//'deg.txt'
          write(*,*)'inputfile is ',inputfile
          write(*,*)'outputfile is ', outputfile


c     count how many lines in this files
c          open(10,file='saf2-left.txt',status='old')
          open(10,file=inputfile,status='old')
            linenum=0
                do
                    read(10,fmt="(A79)",iostat=status)buffer
                    if(status/=0)exit
                    linenum=linenum+1
c                    write(*,"(A79)")buffer
                enddo
          close(10)
          write(*,*)'the total lines of inputfile are ', linenum

c     read the coor from file
          open(10,file=inputfile,status='old')
            do i=1,linenum
                read(10,*)(coor4(j,i),j=1,4)
            enddo
          close(10)
ccc     test the read
cc          do i=1,linenum
cc            write(*,1000)(coor4(j,i),j=1,4)
cc          enddo



c     xy2deg
      do i=1,linenum
        coor4deg(1,i)=coor4(1,i)
        coor4deg(4,i)=coor4(4,i)
        call xy2deg1(coor4(2,i),coor4(3,i),coor4deg(2,i),coor4deg(3,i))
      enddo

ccc     test the xy2deg
cc          do i=1,linenum
cc            write(*,1000)(coor4deg(j,i),j=1,4)
cc          enddo

c      write to the file
      open(11,file=outputfile,status='unknown',
     *   form='formatted')
        do i=1,linenum
            write(11,1000)(coor4deg(j,i),j=1,4)
        enddo
      close(11)



1000  format(f5.1,2f15.5,f10.2)

      end program xy2deg

c%% %%%%%%%%%%%%%%% transfer the meter back to degree
      subroutine xy2deg1(x,y,xdeg,ydeg)
        implicit real*8 (a-h,l,o-z)
        long0=-116.00551
        lat0=33.3025296
        pi=4*datan(1.d0)
c        write(*,*)'pi=', pi
        d=35.d0*pi/180
c     if rotate,rotate back in d, clockwise,
        xtmp=x*cos(d)-y*sin(d)
        ytmp=x*sin(d)+y*cos(d)
        x=xtmp
        y=ytmp
c     transfer meter to degree
        ydeg=lat0+y/111263
        xdeg=long0+x/(111263*abs(cos((pi/180)*(lat0+ydeg)/2)))
        return
      end
